<script setup lang="ts">
import { LogoutApi, UpdateUserInfoApi } from "@/api/user";
import GenderList from "@/components/Gender/index.vue";
import { useUserInfo } from "@/store/user";
import { AIToken, Token } from "@/utils/cache";
import debounce from "@/utils/debounce";
import Lnkyeah from "@/utils/lnkyeah";
import dayjs from "dayjs";
import { storeToRefs } from "pinia";
import { ref, watch, computed } from "vue";
import useBirth from "./useBirth";

type SelectType = "birthday" | "city" | "gender";

interface UserInfoProps {
  profile_photo?: any;
  user_name?: string;
  province?: string;
  city?: string;
  area?: string;
  birthday?: string;
  gender?: string;
  info?: string;
  address?: string;
}

const userStore = useUserInfo();
const { userInfo } = storeToRefs(userStore);
const { getUserInfo, resetUserInfo } = useUserInfo();

const formModelRef = ref<any>(null);

const genderSelectRef = ref<any>(null);
const imageFile = ref<File>();

const formUserInfo = ref<UserInfoProps>({
  profile_photo: userInfo.value.profile_photo,
  user_name: userInfo.value.user_name,
  gender: userInfo.value.gender,
  info: userInfo.value.info
});

const formatGender = computed(() => {
  if (formUserInfo.value.gender === "1") {
    return "男";
  }
  if (formUserInfo.value.gender === "2") {
    return "女";
  }
  return "";
});

//  开启 - 性别 / 所在地 / 生日 - 选择器
const handleHideKeyboard = () => {
  uni.hideKeyboard();
};

const handleChangeShowSelect = (ref: any) => {
  console.log(123);
  if (ref) {
    ref?.open();
    handleHideKeyboard();
  } else return;
};

const handleChangeCloseSelect = (info: any, ref: any, label: SelectType) => {
  if (ref) {
    ref?.close();
  }
  if (label === "gender") {
    formUserInfo.value.gender = info.label_id;
  }
};

watch(
  () => formUserInfo.value.birthday,
  (oldVal, _) => {
    if (oldVal) {
      formUserInfo.value.birthday = String(dayjs(oldVal).format("YYYY-MM-DD"));
    }
  },
  { deep: true }
);

const handleLogout = async () => {
  const { data } = await LogoutApi();
  if (data.error_code === 0) {
    uni.showToast({
      title: "退出成功",
      icon: "success"
    });
    Lnkyeah.instance.closeSocket();
    Token.remove(); // 删除token
    AIToken.remove();
    resetUserInfo();

    uni.switchTab({ url: "/pages/mine/mine" });
  } else {
    uni.showToast({
      title: "服务异常",
      icon: "error"
    });
  }
};

const handleSubmit = debounce(() => {
  formModelRef.value
    .validate()
    .then(async (res: boolean) => {
      if (res) {
        console.log("imageFile", {
          ...formUserInfo.value,
          profile_photo: imageFile.value
        });
        try {
          const res = await UpdateUserInfoApi({
            ...formUserInfo.value,
            profile_photo: imageFile.value || formUserInfo.value.profile_photo
          });
          console.log(res);
          if (res.error_code === 0) {
            getUserInfo();
            uni.switchTab({
              url: "/pages/mine/mine"
            });
          }
        } catch (error) {
          console.log(error);
          uni.showToast({
            icon: "error",
            title: "接口异常"
          });
        }
      }
    })
    .catch(() => {
      uni.showToast({
        icon: "error",
        title: "校验失败"
      });
    });
});
const onUploadAvatar = () => {
  uni.chooseImage({
    type: "image",
    count: 1,
    success(res) {
      // @ts-ignore
      const file = res.tempFiles[0];
      const fileSize = file.size / 1024 / 1024;
      if (fileSize >= 10) {
        uni.showToast({
          title: "文件大小不能超过10M",
          icon: "none"
        });
        return;
      }
      imageFile.value = file;
      formUserInfo.value.profile_photo = file.path;
    }
  });
};
</script>

<template>
  <view class="userInfo">
    <view
      :class="[
        'avatar-content',
        { 'avatar-active': !formUserInfo.profile_photo }
      ]"
      @click="onUploadAvatar"
    >
      <image
        mode="aspectFill"
        class="avatar"
        :src="formUserInfo.profile_photo"
      />
      <!-- <Upload @update-url="handleUpdateAvatar" /> -->
    </view>
    <uv-form
      labelPosition="left"
      :model="formUserInfo"
      ref="formModelRef"
      labelWidth="66"
    >
      <uv-form-item label="姓名" prop="formUserInfo.user_name" borderBottom>
        <uv-input
          v-model="formUserInfo.user_name"
          placeholder="请输入昵称"
          border="none"
        />
      </uv-form-item>
      <uv-form-item label="性别" prop="formUserInfo.gender" borderBottom>
        <view @click="handleChangeShowSelect(genderSelectRef)">
          <uv-input
            v-model="formatGender"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择性别"
            border="none"
          />
        </view>
      </uv-form-item>
      <uv-form-item label="简介" prop="formUserInfo.info" borderBottom>
        <uv-input
          v-model="formUserInfo.info"
          border="none"
          placeholder="请输入简介"
        />
      </uv-form-item>
      <uv-button
        type="primary"
        text="保存"
        customStyle="margin-top: 24px;border-radius: 32px;background: var(--btn-bg-color-active)"
        @click="handleSubmit"
      />
    </uv-form>
    <!-- 性别选择器 -->
    <uv-action-sheet ref="genderSelectRef" title="选择性别" round="15">
      <GenderList
        :current="formUserInfo.gender"
        @on-click="
          info => handleChangeCloseSelect(info, genderSelectRef, 'gender')
        "
      />
    </uv-action-sheet>

    <view class="logout" @click="handleLogout">退出登录</view>
  </view>
</template>

<style lang="scss" scoped>
.userInfo {
  padding: 0 24px;

  .avatar-content {
    position: relative;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    overflow: hidden;
    margin: 60px auto 34px;

    .avatar {
      width: 100%;
      height: 100%;
    }
  }

  .avatar-active {
    background: url("https://wealth-1311286543.cos.ap-guangzhou.myqcloud.com/taoshe/static/mine/default_avatar.svg");
    background-size: cover;
    background-repeat: no-repeat;
    &::after {
      content: "添加头像";
      position: absolute;
      left: 50%;
      bottom: 0;
      transform: translate(-50%);
      width: 100%;
      height: 20px;
      background-color: rgba(0, 0, 0, 0.8);
      font-size: 9px;
      line-height: 20px;
      color: #fff;
      text-align: center;
    }
  }

  .logout {
    position: fixed;
    width: 670rpx;
    bottom: 36px;
    left: 50%;
    transform: translate(-50%);
    color: rgba(51, 51, 51, 0.5);
    text-align: center;
    font-family: "PingFang SC";
    font-size: 28rpx;
    font-style: normal;
    font-weight: 500;
    line-height: 24px;
    // background-color: #333;
    // padding: 16rpx 0;
    // border-radius: 20rpx;
  }
}
</style>
